import sys
import os
import xbmc
import xbmcplugin
import string

CACHE_PATH = xbmc.translatePath( os.path.join( os.getcwd(), 'resources', 'cache' ) )
__plugin__ = "xbVOD"

def Debug(message, Verbose=True):
    bVerbose = xbmcplugin.getSetting( "debug" )
    if (bVerbose == 'true'):
        bVerbose = True
    else:
        bVerbose = False
    
    if (bVerbose and Verbose):
        # repr() is used, got wierd issues with unicode otherwise, since we send mixed string types (eg: unicode and ascii) 
        #xbmc.log( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ), xbmc.LOGNOTICE )
        print( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ))
    elif (not Verbose):
        # repr() is used, got wierd issues with unicode otherwise, since we send mixed string types (eg: unicode and ascii) 
        #xbmc.log( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ), xbmc.LOGNOTICE )
        print( "[PLUGIN] '%s: %s'!" % ( __plugin__, message, ))


def CheckVersion():
    Version = ""
    if (os.path.exists(VERSION_PATH)):
        versionfile = file(VERSION_PATH, 'r')
        Version = versionfile.read()        
    return Version

def WriteVersion(Version):
    print Version
    print VERSION_PATH
    versionfile = file(VERSION_PATH, 'w')
    versionfile.write (Version)
    versionfile.close()

def CheckIfFirstRun():
    global CONFIG_PATH
    if (os.path.exists(CONFIG_PATH)):
        return False
    else:
        return True
    
def CheckIfUpgrade():
    return False

def CheckForNewVersion():
    #Check for new version
    if xbmcplugin.getSetting( "new_ver" ) == "true":
        try:
            import re
            import urllib
            usock = urllib.urlopen(__svn_url__ + "default.py")
            htmlSource = usock.read()
            usock.close()

            version = re.search( "__version__.*?[\"'](.*?)[\"']",  htmlSource, re.IGNORECASE ).group(1)
            Debug ( "SVN Latest Version :[ "+version+"]", True)
            
            if version > __version__:
                import xbmcgui
                dialog = xbmcgui.Dialog()
                selected = dialog.ok('xbMako ' % (str(__version__)),'NEW VERSION AVAILABLE ' % (str(version)),'A new version of xbMako is available.[CR]Check xbmako.googlecode.com for mroe details.')
        except:
            print 'Exception in reading SVN'

def loadCache(filename):
    if xbmcplugin.getSetting( "usecache" ) != "true":
        return False

    filename = filename.replace('.', ''). replace('/','').replace(':','').replace('?','').replace('-','')
    filename = xbmc.translatePath( os.path.join( CACHE_PATH, filename ) ) 
    Debug('Loading from cache: ' + filename)

    title = ""
    plot = ""
    image = ""
    streamurl = ""

    try:
        if (os.path.exists(filename)):
            Debug('Cache hit: ' + filename)
            cachefile = file(filename, 'r')
            filecontents = cachefile.read()
            title = filecontents.split('%%$$')[0]
            plot = filecontents.split('%%$$')[1]
            image = filecontents.split('%%$$')[2]
            streamurl = filecontents.split('%%$$')[3]
        else:
            Debug('Cache miss: ' + filename)
            return False
    except:
        Debug('Cache exception')
        return False
    
    return title, plot, image, streamurl

def saveCache(filename, title, plot, image, streamurl):
    if xbmcplugin.getSetting( "usecache" ) != "true":
        return False
    
    filecontents = title + '%%$$' + plot + '%%$$' + image + '%%$$' + streamurl
    filename = filename.replace('.', ''). replace('/','').replace(':','').replace('?','').replace('-','').replace(';','')
    filename = xbmc.translatePath( os.path.join( CACHE_PATH, filename ) ) 
    Debug('Saving to cache: ' + filename)

    try:
        cachefile = file(filename, 'w')
        cachefile.write (filecontents)
        cachefile.close()
    except:
        Debug('Cache exception')
        return False
    
def clearCache():
    filename = xbmc.translatePath( os.path.join( CACHE_PATH, name ) ) 
